package com.topisv.tms.service.deppon;

import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Date;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.http.NameValuePair;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.WarehouseAddress;
import com.topisv.tms.jms.vo.SendMessage;
import com.topisv.tms.repository.WarehouseAddressDao;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.base.BaseService;
import com.topisv.tms.service.vo.deppon.TransPeopleInfo;
import com.topisv.tms.service.vo.deppon.addAndUpdate.AddAndUpdateOrderReq;
import com.topisv.tms.service.vo.deppon.common.DOPConstans;
import com.topisv.tms.utils.deppon.SecurityUtil;
import com.topisv.tms.utils.enums.JMSMessageType;
import com.topisv.tms.utils.myjson.MyJsDateJsonValueProcessor;

/**
 * 德邦的业务逻辑类
 *  Date          Author       Version       Description
 * ----------------------------------------------------------
 *  2015-6-5      CC            1.0           Create
 */
@Component
public class DepponService extends BaseService {
	@Autowired
	private EdiOrderService ediOrderService;
	@Autowired
	private WarehouseAddressDao warehouseAddressDao;

	public SendMessage createDepponOrder(EdiOrder ediOrder) {
		try {
			Date now = new Date();
			DecimalFormat nf = new DecimalFormat("0000000000000");
			SendMessage message = new SendMessage();
			AddAndUpdateOrderReq depponOrder = new AddAndUpdateOrderReq();
			depponOrder.setLogisticCompanyID(DOPConstans.LOGISTIC_PROVIDERID_DEFAULT);// 固定为DEPPON
			depponOrder.setLogisticID("EPL" + nf.format(ediOrder.getId()));// 订单号
			depponOrder.setMailNo(ediOrder.getMailNo());// 运单号
			depponOrder.setOrderSource(DOPConstans.COMPANY_CODE);// 与companyCode一致
			depponOrder.setServiceType("2");// 在线订单
			depponOrder.setCustomerID(DOPConstans.COMPANY_ID);
			depponOrder.setCustomerCode(DOPConstans.CUSTOMER_CODE);
			WarehouseAddress warehouseAddress = warehouseAddressDao.findByWarehouseCode(ediOrder.getWarehouseCode());
			TransPeopleInfo sender = new TransPeopleInfo();
			sender.setName("派友云仓");
			sender.setPhone(warehouseAddress.getMobile());
			sender.setProvince(warehouseAddress.getProvName());
			sender.setCity(warehouseAddress.getCityName());
			sender.setCounty(warehouseAddress.getDistName());
			sender.setAddress(warehouseAddress.getAddress());
			depponOrder.setSender(sender);
			// 收货人
			TransPeopleInfo receiver = new TransPeopleInfo();
			receiver.setName(ediOrder.getRecena());
			receiver.setMobile(ediOrder.getMobile());
			receiver.setPhone(ediOrder.getTeleph());
			receiver.setProvince(ediOrder.getProvna());
			receiver.setCity(ediOrder.getCityna());
			receiver.setCounty(ediOrder.getDistna());
			receiver.setAddress(ediOrder.getAddres());
			depponOrder.setReceiver(receiver);
			
			depponOrder.setTotalNumber(ediOrder.getSkuQty());
			depponOrder.setTotalWeight(4);//修改默认重量为4kg，方便收货。结算重量还是以现场收货录入为准
			depponOrder.setGmtCommit(now);// 订单提交时间
			depponOrder.setCargoName(getCargoName(ediOrder));
			depponOrder.setPayType(DOPConstans.PAYTYPE_ACCOUNT);
			depponOrder.setTransportType(DOPConstans.TRANSPORT_TYPE_RCP);// 待确认
			depponOrder.setDeliveryType(DOPConstans.PICKUP_TYPE_UPSTAIRS);// 送货上楼
			depponOrder.setBackSignBill(DOPConstans.BACK_SIGN_BILL_NONE);

			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(Date.class, new MyJsDateJsonValueProcessor());

			message.setMessage(JSONObject.fromObject(depponOrder, jsonConfig).toString());
			message.setType(JMSMessageType.CREATE_DEPPON_ORDER.getType());
			return message;
		} catch (Exception e) {
			log.error("error happed.", e);
		}
		return null;
	}

	public SendMessage createDepponOrder(String orderNo) {
		EdiOrder ediOrder = ediOrderService.findByOrdeno(orderNo);
		return createDepponOrder(ediOrder);
	}

	private String getCargoName(EdiOrder order) {
		/*
		 * StringBuilder name = new StringBuilder(); for (EdiOrderItem
		 * ediOrderItem : order.getOrderItems()) {
		 * name.append(ediOrderItem.getNam()); } return name.toString();
		 */
		return "货物";
	}

	/**
	 * 校验德邦是否可达
	 * @param order
	 * @return boolean
	 */
	public boolean checkArrive(EdiOrder order) {
		boolean rs = false;
		try {
			SendMessage message = createDepponOrder(order);
			Response response = sendOutMessage(message.getMessage());
			String responseStr = response.returnContent().asString();
			log.info("deppon {} response {}", order.getId(), responseStr);
			JSONObject json = JSONObject.fromObject(responseStr);
			return "true".equals(json.getString("result"));
		} catch (Exception e) {
			log.error("some error.", e);
		}
		return rs;
	}

	public Response sendOutMessage(String param) throws Exception {
		String timestamp = SecurityUtil.getTimestamp();
		String digest = SecurityUtil.getDigest(new StringBuilder().append(param).append(DOPConstans.APP_KEY).append(timestamp).toString());
		NameValuePair paramsPair = new BasicNameValuePair("params", param);
		NameValuePair digestPair = new BasicNameValuePair("digest", digest);
		NameValuePair timestampPair = new BasicNameValuePair("timestamp", timestamp);
		NameValuePair companyCodePair = new BasicNameValuePair("companyCode", DOPConstans.COMPANY_CODE);
		return Request.Post(DOPConstans.CHECK_ARRIVE_URL).connectTimeout(10000).bodyForm(Arrays.asList(paramsPair, digestPair, timestampPair, companyCodePair), Charset.forName("UTF-8")).execute();
	}

}
